<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <input type="submit" id="addBtn" value="添加一条新的访客信息" />

    <table border="1" cellspacing="0" cellpadding="10">
      <tbody>
        <tr>
          <td>序列号</td>
          <td>姓名</td>
          <td>年龄</td>
          <td>操作</td>
        </tr>
      </tbody>
    </table>

    <script>
      var info = [
        {
          name: "胡杭",
          age: 16,
        },
        {
          name: "胜明",
          age: 22,
        },
        {
          name: "军毅",
          age: 21,
        },
        {
          name: "晓华",
          age: 13,
        },
        {
          name: "盛聪",
          age: 23,
        },
        {
          name: "侦剑",
          age: 32,
        },
        {
          name: "红翔",
          age: 25,
        },
        {
          name: "超维",
          age: 18,
        },
        {
          name: "士琪",
          age: 22,
        },
        {
          name: "艳华",
          age: 20,
        },
      ];

			let tbody = document.querySelector("tbody"),
					addBtn = document.getElementById("addBtn"),
					delBtn = tbody.querySelectorAll("button"),
					i = 0,n = info.length;
      addBtn.onclick = () =>{ 
        if (i < n) {
          let newtr = document.createElement("tr");
					tbody.appendChild(newtr);
          newtr.innerHTML = `
            <td>${i+1}</td>
						<td>${info[i]["name"]}</td>
						<td>${info[i]["age"]}</td>
						<td><button>删除</button></td>`;

					delBtn = tbody.querySelectorAll("button");
					// 遍历给每一个删除按钮绑定点击事件
					delBtn.forEach(el=>{
						el.onclick = () =>{
							el.parentElement.parentElement.remove();
						};
					});


					// for (let i = 0; i < delBtn.length; i++) {
					//     delBtn[i].onclick = function () {
					//         delBtn[i].parentElement.parentElement.remove();
					//     }
					// }

					i++;
				};
      };
    </script>
  </body>
</html>
